﻿package net.wangit.framework.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.wangit.Path;
import net.wangit.framework.exception.ConfigurationException;
import net.wangit.util.XMLUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;


public class MimeSettings {

	private static final Log log = LogFactory
			.getLog(net.wangit.framework.config.MimeSettings.class);
	public static final String DEFAULT = "*";
	public static final String TYPE = "type";
	public static final String EXTENSION = "extension";
	private static final String VALUE = "value";
	private static Map mapping;

	public MimeSettings() {
	}

	public static void load() {
		mapping = new HashMap();
		String path = (new StringBuilder(String.valueOf(Path.getHomePath())))
				.append("/mime.xml").toString();
		try {
			Document document = XMLUtil.parseByPath(path);
			Element root = document.getRootElement();
			List list = root.elements("type");
			for (int i = 0; i < list.size(); i++) {
				Element element = (Element) list.get(i);
				String extension = element.attributeValue("extension");
				String value = element.attributeValue("value");
				mapping.put(extension, value);
			}

		} catch (Exception e) {
			log.error((new StringBuilder("could not load beans: "))
					.append(path).toString(), e);
			throw new ConfigurationException((new StringBuilder(
					"could not load mime: ")).append(path).toString(), e);
		}
	}

	public static String getContentType(String extension) {
		String type = (String) mapping.get(extension);
		return type != null ? type : (String) mapping.get("*");
	}

}
